package com.agriculture.controller;

import com.agriculture.common.OrderStatus;
import com.agriculture.common.R;
import com.agriculture.entity.Orders;
import com.agriculture.service.OrderService;
import com.agriculture.service.UserService;
import com.agriculture.utils.JwtUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.agriculture.entity.User;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private OrderService orderService;


    /**
     * 员工登录
     * @param session
     * @param user
     * @return
     */
    @PostMapping("/login")
    public R<String> login(HttpSession session, @RequestBody User user){

        //1、将页面提交的密码password进行md5加密处理
        String password = user.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getName,user.getName());
        User u = userService.getOne(queryWrapper);

        //3、如果没有查询到则返回登录失败结果
        if(u == null){
            return R.error("登录失败");
        }

        //4、密码比对，如果不一致则返回登录失败结果
        if(!u.getPassword().equals(password)){
            return R.error("登录失败");
        }

        // 5、登录成功，生成令牌，下发令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", u.getId());
        claims.put("name", u.getName());
        claims.put("phone", u.getPhone());
        claims.put("sex", u.getSex());
        claims.put("id_number", u.getIdNumber());
        claims.put("avatar", u.getAvatar());
        claims.put("is_delete", u.getIsDeleted());

        // 根据 user_id 和 status = 1 查找order_id
        LambdaQueryWrapper<Orders> orderWrapper = new LambdaQueryWrapper<>();
        orderWrapper.eq(Orders::getUserId, u.getId());
        orderWrapper.eq(Orders::getStatus, OrderStatus.ToBePaid);
        Orders order = orderService.getOne(orderWrapper);
        // 如果找不到，直接添加到 order 表
        if(order == null){
            Orders newOrder = new Orders();
            newOrder.setUserId(u.getId());
            newOrder.setStatus(OrderStatus.ToBePaid);
            orderService.save(newOrder);
            Orders order2 = orderService.getOne(orderWrapper);
            claims.put("order_id", order2.getId());
        }else{
            // 添加
            claims.put("order_id", order.getId());
        }

        String jwt = JwtUtils.generateJwt(claims);

        //6、登录成功，将员工id 和 token 存入Session并返回登录成功结果
        session.setAttribute("user", u.getId());


        return R.success(jwt);
    }

    /**
     * 根据 token 获取用户信息
     * @param token
     * @return
     */
    @GetMapping("/info/{token}")
    public R info(@PathVariable String token){
        Claims claims = JwtUtils.parseJWT(token);
        return R.success(claims);
    }

    /**
     * 用户注册
     * @param request
     * @param user
     * @return
     */
    @PostMapping("/register")
    public R<String> register(@RequestBody User user){

        if(user.getName() == null || user.getPassword() == null){
            return R.error("用户名或密码不能为空");
        }

        //1、将页面提交的密码password进行md5加密处理
        String password = user.getPassword();
        user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));

        //2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getName,user.getName());
        User u = userService.getOne(queryWrapper);

        //3、如果没有查询到则返回登录失败结果
        if(u == null){
            // 能注册，将数据写进数据库
            userService.save(user);
            return R.success("注册成功");
        }else{
            // 不能注册
            return R.error("用户名重复");
        }
    }

    /**
     * 员工退出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        //清理Session中保存的当前登录员工的id
        request.getSession().removeAttribute("user");
        return R.success("退出成功");
    }
}





















